import jwt from "jsonwebtoken";

const secret = "935WmongoGsdalkfnxRvmas";

interface ITHasLoginUser {
  id: string;
  token: string;
}

//白名单
export const whiteList = [
  "/login",
  "/register",
  "/language/all",
  "/print",
  //   "/designer/detail",
  "/reagent/allreagent",
  //   "/dictionary/fulldict",
  "/user/checkuser",
  "/user/changepassword",
];

// token黑名单，用于注销，单一登录等
export const blackTokens: string[] = [];

export const hasLoginUser: ITHasLoginUser[] = [];

//生成token
export const createToken = (info: any) => {
  let token = jwt.sign(info, secret, {
    //Token有效时间 单位s， 这里设置24小时
    expiresIn: 60 * 60 * 24,
  });
  return token;
};

//验证Token
export const verifyToken = (token: any) => {
  return new Promise((resolve, reject) => {
    jwt.verify(token, secret, (error: any, result: any) => {
      if (error) {
        reject(error);
      } else {
        resolve(result);
      }
    });
  });
};

// 销毁Token
export const destroyToken = (token: string) => {
  blackTokens.push(token);
};

export const isDestroyToken = (token: string) => {
  let isInDestroy = false;
  blackTokens.some((item) => {
    if (item === token) {
      isInDestroy = true;
    }
    return false;
  });
  return isInDestroy;
};

// 判断是否登录，是:返回token， 否：返回null
export const getLoginUserToken = (userId: string): string => {
  let loginToken = "";
  hasLoginUser.some(({ id, token }) => {
    if (id === userId) {
      loginToken = token;
      return true;
    }
    return false;
  });
  return loginToken;
};

// 暂存已经登录用户信息
export const addLoginUser = (data: ITHasLoginUser) => {
  const { id } = data;
  const hasLoginToken = getLoginUserToken(id);
  if (hasLoginToken) {
    let hasIndex = -1;
    hasLoginUser.some((item, index) => {
      if (item.id === id) {
        hasIndex = index;
        return true;
      }
      return false;
    });
    hasLoginUser.splice(hasIndex, 1);
  }
  hasLoginUser.push(data);
};

export const removeLoginUser = (data: string) => {
  let hasIndex = -1;
  hasLoginUser.some((item, index) => {
    if (item.id === data) {
      hasIndex = index;
      return true;
    }
    return false;
  });
  hasLoginUser.splice(hasIndex, 1);
};
